import clientEnum from "./client.enum"
import clientFunc from "./client.func"
import CollectionObserverAdaptor from "./CollectionObserverAdaptor"

export default class Sensor_Sensor {
  id: any
  sensorCalls: any
  sensorState: any
  readingCollection: any
  origin: { x: number; y: number; z: number }
  forward: { x: number; y: number; z: number }
  sources: any[]
  stateObservingCancellable: any
  constructor(t, e, s, i) {
    this.id = t
    this.sensorCalls = e
    this.sensorState = s
    this.readingCollection = i
    this.origin = { x: 0, y: 0, z: 0 }
    this.forward = { x: 0, y: 0, z: -1 }
    this.sources = []
    this.stateObservingCancellable = s.subscribe(
      new (class SensorObserver {
        sensor: any
        constructor(t) {
          this.sensor = t
        }
        onChanged(t) {
          clientFunc.at(this.sensor.origin, t.origin), clientFunc.at(this.sensor.forward, t.forward)
        }
      })(this)
    )
  }
  dispose() {
    this.sensorCalls.dispose(this.id), this.stateObservingCancellable.cancel()
  }
  get facade() {
    const t = this
    class ObserverAdaptor {
      observer: any
      constructor(t) {
        this.observer = t
      }
      onChanged() {
        try {
          this.observerIsCallback(this.observer) ? this.observer(e) : this.observer.onChanged(e)
        } catch (t) {
          throw Error("The argument provided to subscribe was not a valid observer\nExpected a function or an object with an `onChanged` function")
        }
      }
      observerIsCallback(t) {
        return !t.onChanged
      }
    }
    class ConditionAdaptor {
      condition: any
      constructor(t) {
        this.condition = t
      }
      waitUntil() {
        try {
          return this.conditionIsCallback(this.condition) ? this.condition(e) : this.condition.waitUntil(e)
        } catch (t) {
          throw Error("The argument provided to subscribe was not a valid waiter\nExpected a function or an object with an `waitUntil` function")
        }
      }
      conditionIsCallback(t) {
        return !t.waitUntil
      }
    }
    const e = {
      get origin() {
        return t.origin
      },
      get forward() {
        return t.forward
      },
      addSource(...e) {
        t.addSource(...e)
      },
      showDebug(e) {
        t.sensorCalls.showDebug(t.id, e)
      },
      readings: { subscribe: e => t.readingCollection.subscribe(new CollectionObserverAdaptor(e, t.sources)) },
      dispose() {
        t.dispose()
      },
      subscribe: e => t.sensorState.subscribe(new ObserverAdaptor(e)),
      waitUntil: e => t.sensorState.waitUntil(new ConditionAdaptor(e))
    }
    return e
  }
  async addSource(...t) {
    this.sources.push(...t)
    const e = []
    for (const s of t) {
      const t = clientEnum.ot.map.get(s)
      if (!t) throw Error(s + " was not a valid source. Sources must be created using createSource")
      t.id && e.push(t.id)
    }
    this.sensorCalls.addSource(this.id, ...e)
  }
}
